// 在管理后台的index.html底部script标签前添加以下JavaScript函数

// ========== 二维码管理相关函数 ==========

// 生成单个二维码
async function generateSingleQR() {
    const assetId = document.getElementById('singleAssetId').value.trim();
    const domain = document.getElementById('qrDomain').value.trim();

    if (!assetId) {
        alert('请输入资产ID');
        return;
    }

    if (!domain) {
        alert('请输入域名');
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/qrcode/generate`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                assetId: parseInt(assetId),
                domain: domain,
                adminKey: ADMIN_KEY
            })
        });

        const data = await response.json();

        if (data.success && data.data) {
            document.getElementById('resultSingleAssetId').textContent = assetId;
            document.getElementById('resultSingleURL').textContent = data.data.qrCodeUrl;
            document.getElementById('singleQRResult').style.display = 'block';
            alert('✅ 二维码URL生成成功！');
            // 刷新列表
            loadQRCodeList();
        } else {
            alert('生成失败: ' + (data.message || '未知错误'));
        }
    } catch (error) {
        console.error('生成失败:', error);
        alert('生成失败: ' + error.message);
    }
}

// 批量生成二维码
async function generateBatchQR() {
    const assetIdsText = document.getElementById('batchAssetIds').value.trim();
    const domain = document.getElementById('qrDomain').value.trim();

    if (!assetIdsText) {
        alert('请输入资产ID列表');
        return;
    }

    if (!domain) {
        alert('请输入域名');
        return;
    }

    const assetIds = assetIdsText.split('\n')
        .map(id => id.trim())
        .filter(id => id)
        .map(id => parseInt(id));

    if (assetIds.length === 0) {
        alert('没有有效的资产ID');
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/qrcode/generate-batch`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                assetIds: assetIds,
                domain: domain,
                adminKey: ADMIN_KEY
            })
        });

        const data = await response.json();

        if (data.success && data.data) {
            let html = '<div style="padding:15px;background:#f6ffed;border:1px solid #b7eb8f;border-radius:6px;margin-bottom:10px;">';
            html += '<strong style="color:#52c41a;">✅ 批量生成完成！</strong>';
            html += '</div>';
            html += '<table style="width:100%;border-collapse:collapse;">';
            html += '<tr style="background:#f0f0f0;"><th style="padding:10px;border:1px solid #ddd;">资产ID</th><th style="padding:10px;border:1px solid #ddd;">状态</th><th style="padding:10px;border:1px solid #ddd;">二维码URL</th></tr>';

            data.data.results.forEach(item => {
                const statusColor = item.status === 'success' ? '#52c41a' : '#f5222d';
                html += `<tr>
                    <td style="padding:10px;border:1px solid #ddd;">${item.assetId}</td>
                    <td style="padding:10px;border:1px solid #ddd;color:${statusColor};">${item.status === 'success' ? '✓ 成功' : '✗ 失败'}</td>
                    <td style="padding:10px;border:1px solid #ddd;font-size:11px;word-break:break-all;">${item.qrCodeUrl || item.message || '-'}</td>
                </tr>`;
            });

            html += '</table>';
            document.getElementById('batchQRResult').innerHTML = html;

            alert('✅ 批量生成完成！');
            // 刷新列表
            loadQRCodeList();
        } else {
            alert('批量生成失败: ' + (data.message || '未知错误'));
        }
    } catch (error) {
        console.error('批量生成失败:', error);
        alert('批量生成失败: ' + error.message);
    }
}

// 填充未配置二维码的设备
async function fillUnassignedAssets() {
    try {
        const response = await fetch(`${API_BASE}/asset/list`);
        const data = await response.json();

        if (data.code === 0 && data.data) {
            const unassigned = data.data.filter(asset => !asset.qr_code);
            const ids = unassigned.map(asset => asset.id).join('\n');
            document.getElementById('batchAssetIds').value = ids;
            alert(`已填充 ${unassigned.length} 个未配置二维码的设备`);
        }
    } catch (error) {
        console.error('获取未配置设备失败:', error);
        alert('获取设备列表失败');
    }
}

// 填充所有设备
async function fillAllAssets() {
    try {
        const response = await fetch(`${API_BASE}/asset/list`);
        const data = await response.json();

        if (data.code === 0 && data.data) {
            const ids = data.data.map(asset => asset.id).join('\n');
            document.getElementById('batchAssetIds').value = ids;
            alert(`已填充所有 ${data.data.length} 个设备`);
        }
    } catch (error) {
        console.error('获取设备列表失败:', error);
        alert('获取设备列表失败');
    }
}

// 加载已生成二维码的设备列表
async function loadQRCodeList() {
    try {
        const response = await fetch(`${API_BASE}/asset/list`);
        const data = await response.json();

        if (data.code === 0 && data.data) {
            const assetsWithQR = data.data.filter(asset => asset.qr_code);
            renderQRCodeList(assetsWithQR);
        }
    } catch (error) {
        console.error('加载二维码列表失败:', error);
    }
}

// 渲染二维码列表
function renderQRCodeList(assets) {
    const tbody = document.getElementById('qrCodeList');

    if (!assets || assets.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><div class="empty-icon">📭</div><div>暂无已生成二维码的设备</div></td></tr>';
        return;
    }

    let html = '';
    assets.forEach(asset => {
        html += `<tr>
            <td>${asset.id}</td>
            <td>${asset.asset_code || '-'}</td>
            <td>${asset.name || '-'}</td>
            <td>${asset.lab_name || asset.lab_id || '-'}</td>
            <td style="font-size:11px;word-break:break-all;">${asset.qr_code}</td>
            <td><span class="badge badge-user">✓ 已生成</span></td>
            <td>
                <button class="btn btn-primary" style="padding:5px 12px;font-size:12px;" onclick="copyQRCode('${asset.qr_code}')">📋 复制URL</button>
                <button class="btn btn-success" style="padding:5px 12px;font-size:12px;margin-left:5px;" onclick="openQRGenerator('${asset.qr_code}')">🖼️ 生成图片</button>
            </td>
        </tr>`;
    });

    tbody.innerHTML = html;
}

// 复制二维码URL
function copyQRCode(url) {
    navigator.clipboard.writeText(url).then(() => {
        alert('✅ 二维码URL已复制到剪贴板！');
    }).catch(() => {
        prompt('请手动复制以下URL:', url);
    });
}

// 打开在线二维码生成器
function openQRGenerator(url) {
    window.open(`https://cli.im/?text=${encodeURIComponent(url)}`, '_blank');
}
